package com.jsbb.interceptor;

import com.alibaba.fastjson.JSON;
import com.jsbb.common.Message;
import com.jsbb.common.UserToken;
import com.jsbb.constant.BizConstant;
import com.jsbb.enums.HttpResponse;
import com.jsbb.util.CookieUtils;
import com.jsbb.util.JwtUtils;
import com.jsbb.util.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 权限拦截器
 *
 * @author w
 * @date 2021-03-05
 */
@Slf4j
public class AuthorityInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        String token = request.getHeader("token");
        if (token == null) {
            token = CookieUtils.getCookie(request, BizConstant.COOKIE_NAME);
        }
        String user = JwtUtils.parse(token);
        log.info("url==={},token==={}", uri, token);
        if (!StringUtils.hasLength(token) && !StringUtils.hasLength(user)) {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter pw = response.getWriter();
            pw.write(JSON.toJSONString(Message.error(HttpResponse.TOKEN_INVALID)));
            pw.flush();
            pw.close();
            return false;
        }
        UserToken userToken = (UserToken) RedisUtils.get(BizConstant.USER_TOKEN + token);
        if (userToken == null) {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter pw = response.getWriter();
            pw.write(JSON.toJSONString(Message.error(HttpResponse.TOKEN_INVALID)));
            pw.flush();
            pw.close();
            return false;
        }
        //用户信息写入redis
        RedisUtils.set(BizConstant.USER_TOKEN + token, userToken, 1800);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e) {

    }
}
